package com.sxt.service.impl;

import com.sxt.common.CodeMsg;
import com.sxt.common.Constant;
import com.sxt.common.PageInfo;
import com.sxt.common.Result;
import com.sxt.dao.UserDao;
import com.sxt.pojo.User;
import com.sxt.service.IUserService;

import java.util.List;
import java.util.Map;

public class UserServiceImpl implements IUserService {
    UserDao userDao = new UserDao();

    @Override
    public Result login(String username, String password) {
        User user = userDao.selectByNameAndPassword(username,password);
        //校验是否存在用户 不存在 说明用户名密码错误
        if (user == null){
            return new Result(CodeMsg.USER_NAME_PASSWORD_ERROR);
        }
        //校验用户的状态
        if (Constant.USER_DELETE_ED.equals(user.getDeleted())){
            return  new Result(CodeMsg.USER_DELETED_ERROR);
        }
        //将用户信息放入result中是为了在servlet中放入session
        return new Result(user);
    }

    @Override
    public Result queryPage(Map<String, String> params, Integer pageNo, Integer pageSize) {
       PageInfo<User> data = userDao.selectPage(params,pageNo,pageSize);
        return new Result(data);

    }

    @Override
    public Result resetPassword(String id) {
        userDao.updatePassword(id,Constant.DEFAULT_PASSWORD);
        return new Result();
    }

    @Override
    public Result delete(String id) {
        //根据员工id 查询关联的客户 如果员工存在光临客户 则无法离职
        userDao.delete(id,Constant.USER_DELETE_ED);
        return new Result();
    }

    @Override
    public Result add(String realname, String username, String role) {
        //校验用户名是否存在
        //根据用户名查询用户
        User user = userDao.selectByUsername(username);
        if (user != null){
            return new Result(CodeMsg.USER_USERNAME_EXIST_ERROR);
        }
        userDao.insert(username,Constant.DEFAULT_PASSWORD,realname,role,Constant.CUSTOMER_DELETE_NOT);
        return new Result();
    }

    @Override
    public Result queryAllSalesmans() {
       List<User> users = userDao.selectList(Constant.USER_DELETE_NOT,Constant.USER_ROLE_SALESMAN);
        return new Result(users);
    }

    @Override
    public Result updatePassword(Integer id, String newPassword) {
        userDao.updatePassword(id.toString(),newPassword);
        return new Result();
    }
}
